package com.link510.aitools.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import androidx.annotation.RequiresPermission;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.Utils;
import com.google.common.base.Strings;
import com.link510.aitools.R;
import com.link510.aitools.core.helper.Network2kUtils;
import com.link510.aitools.framework.activity.BaseAcitivity;
import com.link510.aitools.services.CustomWaitDialogUtils;

import butterknife.BindView;
import butterknife.OnClick;

import static android.Manifest.permission.ACCESS_WIFI_STATE;

public class NetWorkTestActivity extends BaseAcitivity {

    private CustomWaitDialogUtils customWaitDialogUtils;

    @BindView(R.id.logs_TextView)
    TextView logsTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_work_test);
        customWaitDialogUtils = new CustomWaitDialogUtils(mContext);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.FIRST, 1, 2001, "关闭");
        return super.onCreateOptionsMenu(menu);
    }


    // 菜单的监听方法
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == 1 && item.getOrder() == 2001) {
            NetWorkTestActivity.this.finish();
        }

        return true;
    }

    @OnClick(R.id.network_test_button)
    public void networkTestClick() {

        new Thread(() -> {

            customWaitDialogUtils.show("开始网络测....");
            try {

                do {

                    if (!NetworkUtils.isConnected()) {
                        appendTextView(logsTextView, "手机网络没有连接...");
                        break;
                    }

                    appendTextView(logsTextView, "手机网络连接正常...");


                    if (!NetworkUtils.isAvailableByPing("127.0.0.1")) {
                        appendTextView(logsTextView, "手机网络协议异常...");
                        break;
                    }

                    appendTextView(logsTextView, "手机网络协议正常...");

                    if (!NetworkUtils.getWifiEnabled()) {
                        appendTextView(logsTextView, "手机Wi-Fi未打开...");
                        break;
                    }

                    appendTextView(logsTextView, "手机Wi-Fi正常...");


                    if (!NetworkUtils.isAvailableByPing(Network2kUtils.getInstance().getLocalCurrentIpAddr())) {
                        appendTextView(logsTextView, "手机网络模块异常...");
                        break;
                    }
                    appendTextView(logsTextView, "手机网络模块正常...");

                    /*
                     * 获取IP Wifi
                     */
                    String gatewayIPAddress = NetworkUtils.getGatewayByWifi();

                    if (!NetworkUtils.isAvailableByPing(gatewayIPAddress)) {
                        appendTextView(logsTextView, "手机局域网络异常...");
                        break;
                    }
                    appendTextView(logsTextView, "手机局域网络正常...");

                    if (Strings.isNullOrEmpty(Network2kUtils.getInstance().getLocalCoreBroadIpAddr())) {
                        appendTextView(logsTextView, "核心板未找到或网络异常,尝试重新扫描...");
                        Network2kUtils.getInstance().searchCorbroadIP();
                    }

                    if (Strings.isNullOrEmpty(Network2kUtils.getInstance().getLocalCoreBroadIpAddr())) {
                        appendTextView(logsTextView, "核心板未找到或网络异常...");
                    }

                    if (!NetworkUtils.isAvailableByPing(Network2kUtils.getInstance().getLocalCoreBroadIpAddr())) {
                        appendTextView(logsTextView, "核心板网络(" + Network2kUtils.getInstance().getLocalCoreBroadIpAddr() + ")异常...");
                    } else {
                        appendTextView(logsTextView, "核心板网络正常...");
                        appendTextView(logsTextView, "核心板网络IP:" + Network2kUtils.getInstance().getLocalCoreBroadIpAddr() + "...");
                    }

                    /*
                     * 摄像机
                     */
                    String cameraIP = "192.168.1.2";

                    if (!NetworkUtils.isAvailableByPing(cameraIP)) {
                        appendTextView(logsTextView, "摄像机网络异常...");
                    } else {
                        appendTextView(logsTextView, "摄像机网络正常...");
                    }
                    /*
                     * DNS
                     */
                    String dnsIPAddr = getDnsIpAddressByWifi();

                    if (!NetworkUtils.isAvailableByPing(dnsIPAddr)) {
                        appendTextView(logsTextView, "本地路由网络DNS(" + dnsIPAddr + ")异常...");
                        /*
                         * DNS
                         */
                        String gloablDnsIP = "114.114.114.114";

                        if (!NetworkUtils.isAvailableByPing(gloablDnsIP)) {
                            appendTextView(logsTextView, "网络DNS(114.114.114.114)异常,可能外网发生异常,请联系运营商...");
                        } else {
                            appendTextView(logsTextView, "网络DNS(114.114.114.114)正常,请更换正确的DNS服务器...");
                        }
                    } else {
                        appendTextView(logsTextView, "本地路由网络DNS(" + dnsIPAddr + ")正常...");
                    }



                    /*
                     * 网关服务器
                     */
                    String serviceIP = "iot.510link.com";


                    if (!NetworkUtils.isAvailableByPing(serviceIP)) {
                        appendTextView(logsTextView, "网关服务器(" + serviceIP + ")异常...");
                    } else {
                        appendTextView(logsTextView, "网关服务器" + serviceIP + "正常...");
                    }

                } while (false);

                appendTextView(logsTextView, "测试完成...");

            } finally {
                //Login3Activity.this.runOnUiThread(() -> testButton.setEnabled(true));
                customWaitDialogUtils.close();
            }
        }).

                start();


    }

    /**
     * 日志处理
     *
     * @param view
     * @param msg
     */
    private void appendTextView(TextView view, String msg) {

        if (view == null || Strings.isNullOrEmpty(msg)) {
            return;
        }

        NetWorkTestActivity.this.runOnUiThread(() -> {
            view.append(msg + "\n");
            customWaitDialogUtils.show(msg);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customWaitDialogUtils != null) {
            customWaitDialogUtils.dismiss();
        }
    }

    /**
     * Return the ip address by wifi.
     *
     * @return the ip address by wifi
     */
    @RequiresPermission(ACCESS_WIFI_STATE)
    public static String getDnsIpAddressByWifi() {
        @SuppressLint("WifiManagerLeak")
        WifiManager wm = (WifiManager) Utils.getApp().getSystemService(Context.WIFI_SERVICE);
        if (wm == null) return "";
        return Formatter.formatIpAddress(wm.getDhcpInfo().dns1);
    }
}